package com.cy.store.controller;

import com.cy.store.pojo.Address;
import com.cy.store.service.IAddressService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @PROJECT_NAME: store
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/11/5 15:15
 */
@RequestMapping("address")
@RestController
public class AddressController   extends  BaseController{
    @Autowired
    private IAddressService addressService;

    /**
     * 添加新的收货地址
     * @param address
     * @param session
     * @return
     */
    @RequestMapping("add_new_address")
    public JsonResult<Void> addNewAddress(Address address,
                                          HttpSession session){
        String usernameFromSession = getUsernameFromSession(session);
        Integer uidFromSession = getUidFromSession(session);
        addressService.addNewAddress(address,uidFromSession,usernameFromSession);

        return  new JsonResult<>(OK);
    }

    /**
     * 查询当前用户的所有收货地址
     * @param session
     * @return
     */
    @RequestMapping({"/",""})
    public JsonResult<List<Address>> getByUid(HttpSession session){
        Integer uid = getUidFromSession(session);
        List<Address> byUid = addressService.getByUid(uid);
        return new JsonResult<List<Address>>(OK,byUid);
    }

    /**
     * 设置当前用户的默认收货地址
     * @param session
     * @param aid
     * @return
     * //RestFul
     */
    @RequestMapping("{aid}/update_is_default")
    public JsonResult<Void> updateDefault(HttpSession session,@PathVariable("aid") Integer aid){
        String username = getUsernameFromSession(session);
        Integer uid = getUidFromSession(session);
        addressService.setDefault(aid,uid,username);
        return  new JsonResult<Void>(OK);
    }

    /**
     * 删除某条收货地址功能
     * @param session
     * @param aid
     * @return
     */
    @RequestMapping("{aid}/delete_by_aid")
    public JsonResult<Void> delete_by_aid(HttpSession session, @PathVariable("aid")Integer aid){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.deleteAddress(uid,aid,username);

        return new JsonResult<Void>(OK);
    }
}
